<!-- 租户成员 -->
<template>
  <div>
    <!-- :rowSelection="rowSelection" -->
    <BasicTable @register="registerTable" >
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleAddTenantMember"> 添加成员</a-button>
        <a-button type="primary" preIcon="ant-design:edit-outlined" @click="handleOpenInviteLinkList"> 邀请记录</a-button>
        <a-button type="primary" preIcon="ant-design:import-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
        <!-- <a-button type="primary" @click="openModal(true, {})" preIcon="ant-design:hdd-outlined"> 回收站</a-button> -->
        <JThirdAppButton biz-type="user" :selected-row-keys="selectedRowKeys" syncToApp syncToLocal @sync-finally="onSyncFinally" />
    
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
    </BasicTable>
    <!--用户抽屉-->
    <UserForm @register="registerInputForm" @success="handleSuccess" />
    <UserDetails @register="registerDetail"/>
    <!--回收站-->
    <UserRecycleBin @register="registerModal" @success="reload" />
    <!--用户选择弹窗-->
    <SelectUserJoin @register="registerAddUserModal" @select="submitSelectedUser" />
    <InviteUserList @register="registerInviteLinkList" />
    <SubjectAuthorize :config="subjectAuthorizeConfig" @register="registerSubjectAuthorize"/>
  </div>
</template>

<script lang="ts" name="tenant-member" setup>
  import { ref, computed, unref } from "vue"
  import { BasicTable, TableAction, ActionItem } from "/@/components/Table"
  import { Auth } from "/@/enums/authEnum"
  import UserForm from "./components/UserForm.vue"
  import UserDetails from "./components/UserDetails.vue"
  import UserRecycleBin from "./components/UserRecycleBin.vue"
  import JThirdAppButton from "/@/components/jeecg/thirdApp/JThirdAppButton.vue"
  import SelectUserJoin from "./SelectUserJoin.vue"
  import InviteUserList from "./components/InviteUserList.vue"
  import { useDrawer } from "/@/components/Drawer"
  import { useListPage } from "/@/hooks/system/useListPage"
  import { useModal } from "/@/components/Modal"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { columns, searchFormSchema } from "./user.data"
  import * as userApi  from "/@/api/sys/user"
  import { SubjectAuthorize } from "/@/components/My/SubjectAuthorize/index"
  import { listTenantUser, deleteUser, assignUser, batchDeleteUser, getImportUrl, getExportUrl } from "./user.api"
  import { Icon } from "/@/components/Icon"
  import * as ramApi from "/@/api/sys/ram"
  // import { usePermission } from '/@/hooks/web/usePermission'
  // const { hasPermission } = usePermission();

  const { createMessage, createConfirm } = useMessage()
  const [registerSubjectAuthorize, { openModal: openSubjectAuthorize }] = useModal()
  const [registerInputForm, { openDrawer: openInputForm }] = useDrawer()
  const [registerDetail, { openDrawer: openDetail }] = useDrawer()
  const [registerModal, { openModal }] = useModal()
  const [registerAddUserModal, { openModal: openAddUserModal }] = useModal()
  const [registerInviteLinkList, { openModal: openInviteLinkList }] = useModal()

  const subjectAuthorizeConfig = ref<any>({
    querySubjectMenuApi: userApi.listPermission,
    assignSubjectPermPolicyApi: ramApi.assignPermPolicyToUser,
    assignSubjectMenuApi: async (params) => {
      return await userApi.saveUserPermission({
        userId: params.subjectIds[0],
        ...params
      }) 
    },
    success: () => {
      console.log("操作成功")
    }
  })

  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    designScope: "user-list",
    tableProps: {
      title: "用户列表",
      api: listTenantUser,
      bordered: false,
      columns: columns,
      size: "small",
      formConfig: {
        labelWidth: 70,
        schemas: searchFormSchema,
      },
      actionColumn: {
        width: 140,
        title: "操作",
        dataIndex: "action",
        fixed: "right",
        slots: { customRender: "action" },
      },
      beforeFetch: (params) => {
        return Object.assign({ column: "createTime", order: "desc" }, params)
      },
    },
    exportConfig: {
      name: "用户列表",
      url: getExportUrl,
    },
    importConfig: {
      url: getImportUrl,
    },
  })

  const [registerTable, { reload, updateTableDataRecord }, { rowSelection, selectedRowKeys }] = tableContext

  const handleAddTenantMember = () => openAddUserModal(true, { inviteWay: "fromLink", selectPlatformUser: true })
  const handleOpenInviteLinkList = () => openInviteLinkList(true, {})

  const submitSelectedUser = async (selectRows) => {
    const userIds = selectRows.map((e) => e.id)
    console.log("selectRows", selectRows)

    await assignUser({ userIds }, () => {
      createMessage.success("添加成功")
      reload()
    })
  }

  async function handleEdit(record: Recordable) {
    openInputForm(true, {
      record,
      isUpdate: true
    })
  }

  async function handleDetail(record: Recordable) {
    openDetail(true, { record })
  }

  async function handleDelete(record) {
    if (checkeUser(record)) {
      createMessage.warning("不允许操作拥有者")
      return
    }
    createConfirm({
      title: "危险操作",
      content: `确定要删除 ${record.userName} 用户吗？此操作不可逆数据`,
      iconType: "warning",
      onOk: () => deleteUser({ id: record.id }, reload)
    })
  }

  async function batchHandleDelete() {
    await batchDeleteUser({ ids: selectedRowKeys.value }, () => {
      selectedRowKeys.value = []
      reload()
    })
  }

  function handleSuccess({ values }) {
    reload()
    updateTableDataRecord(values.id, values)
    createMessage.success("编辑成功")
  }

  /**
   *同步钉钉和微信回调
   */
  function onSyncFinally({ isToLocal }) {
    // 同步到本地时刷新下数据
    if (isToLocal) {
      reload()
    }
  }

  function getTableAction(record): ActionItem[] {
    return [
      {
        label: "详情",
        onClick: handleDetail.bind(null, record),
      },
      {
        label: "移除",
        ifShow: () => !checkeUser(record),
        color: "error",
        popConfirm: {
          title: "是否确认移除",
          confirm: handleDelete.bind(null, record),
        },
      }
    ]
  }

  const checkeUser = (record) => {
    // 不能操作租户拥有者, 其余都可以操作
    return record.roleList
      .map((e) => e.roleCode)
      .join(",")
      .includes("owner")
  }

  function getDropDownAction(record): ActionItem[] {
    return [
      {
        label: "编辑",
        onClick: handleEdit.bind(null, record),
        ifShow: () => !checkeUser(record),
      },
      {
        label: "授权",
        auth: Auth.assignUserPermission,
        onClick: handleSubjectAuthorize.bind(null, record),
        ifShow: () => !checkeUser(record)
      },
    ]
  }


  const handleSubjectAuthorize = (record) => {
    openSubjectAuthorize(true, { 
      subjectId: record.id,
      subjectType: '2',
      subjectName: record.userName
    })
  }
</script>

<style scoped></style>
